from hqyj_mqtt import MQTTClient   # 从hqyj_mqtt文件将Mqtt_Clt导入进来
import time  # 导入延时
import json   # 导入json模块用来处理mqtt接收数据
import queue
import threading

import base64 # 用来进行图片的base64解码
import cv2   # 用来处理图像数据
import numpy as np  # 用来存储图像数据



'''
     将所有货物全部推到一号仓库
'''
def TransferFruit():
     while True:
          # 推出一号推杆
          mqtt_clint.control_device('rod_control', 'first_push')
          time.sleep(1)
          mqtt_clint.control_device('rod_control', 'all_pull')
          time.sleep(0.5)
def pullFisrtrod():
     mqtt_clint.control_device('rod_control', 'second_pull')

# 创建一个消息队列
msg_queue = queue.Queue()
# 定义回调函数
def custom_on_message(client, userdata, message):
     msg = json.loads(message.payload.decode())  # 将字符串类型转换成键值对
     msg_queue.put(msg)
     print(msg)  # 输出接收到的内容


# 构造mqtt客户端
mqtt_clint =  MQTTClient('127.0.0.1','bb','aa')

# 连接mqtt客户端
mqtt_clint.connect()

# 注册接收回调函数
mqtt_clint.set_on_message(custom_on_message)

# 控制传送带运行
mqtt_clint.control_device('conveyor','run')
# 拉回所有推杆
mqtt_clint.control_device('rod_control','all_pull')
time.sleep(0.5)

# 开启传送水果任务线程
threading.Thread(target=TransferFruit).start()

# 实时处理接收任务
while True:
     json_msg =   msg_queue.get()  # 从队列里面获取数据
     # 判断第一光电对管数据是否为false，如果是，控制推杆推出货物
     if 'first_switch' in json_msg:   # 判断是否为第一个光电对管数据
         value =  json_msg['first_switch']   # 取出光电对管数据的值
         if not value:  # 如果为false则控制推杆
              # 推出二号推杆
              mqtt_clint.control_device('rod_control', 'second_push')
              threading.Timer(0.5,pullFisrtrod).start()
     if 'image' in json_msg:
          # 将Base64编码的图像数据解码为二进制数据
          image_data = base64.b64decode(json_msg['image'])
          # 将二进制数据转换为numpy数组
          image_array = np.frombuffer(image_data, np.uint8)
          # 将numpy数组转换为OpenCV图像对象
          image = cv2.imdecode(image_array, cv2.IMREAD_COLOR)
          cv2.imshow('image',image)
          cv2.waitKey(1)
